﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using LevenBlog.Core.Data;
using LevenBlog.Core.Entities;
using LevenBlog.Core.Utils;
using LevenBlog.Core.Service;
using LevenBlog.Core.Mvc;
using LevenBlog.Core.Cache;
using LevenBlog.Core.User;

namespace LevenBlog.Web.Controllers
{
    [HandleBlogError]
    [ValidateInput(false)]
    public class UserController : BlogBaseController
    {
        public UserController()
        {
            
        }

        [ActionName("login")]
        public ActionResult Login()
        {
            title = "用户登录 - " + Config.Get(Provider).title;
            return View("login");
        }

        [ActionName("checklogin")]
        public ActionResult CheckLogin(string username, string password, string code, int? savetime)
        {
            if (Fetch.IsPostFromAnotherDomain)
                return Message("提交数据非法", "请勿从非法站点提交数据.", MessageIcon.Error);
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(code))
            {
                return Message("信息不完整", "用户名,密码,验证码不能为空,请重新填写. ", MessageIcon.Error);
            }
            if (!savetime.HasValue)
                return Message("Cookie设置错误", "Cookie保持设置错误.", MessageIcon.Error);
            DateTime cookieTime = DateTime.Now;
            switch (savetime.Value)
            {
                case 0:
                    cookieTime = DateTime.MinValue;
                    break;
                case 1:
                    cookieTime = cookieTime.AddDays(1);
                    break;
                case 2:
                    cookieTime = cookieTime.AddMonths(1);
                    break;
                case 3:
                    cookieTime = cookieTime.AddYears(1);
                    break;
                default:
                    cookieTime = DateTime.MaxValue;
                    break;
            }
            HttpCookie codeCookie = Request.Cookies.Get(WebConfig.PrefixKey + "CheckCode");
            if (codeCookie == null)
            {
                return Message("验证码过期", "验证码过期,请返回重新输入.", MessageIcon.Error);
            }
            else
            {
                if (code.ToLower().ToMD5() != codeCookie.Value)
                    return Message("验证码错误", "验证码输入错误,请返回重新上输入.", MessageIcon.Error);
                else
                    Response.Cookies.Remove(WebConfig.PrefixKey + "CheckCode");
            }
            bool result = false;
            if (cookieTime != DateTime.MaxValue && cookieTime != DateTime.MinValue)
            {
                result = Membership.Login(username, password, cookieTime);
            }
            else
            {
                result = Membership.Login(username, password);
            }
            if (!result)
            {
                return Message("用户登陆错误", "对不起,您输入的用户名或者密码有误,请返回重写输入.", MessageIcon.Error);
            }
            else
            {
                return Message("登陆成功", string.Format("<strong>{0}</strong>,欢迎您再次光临.", Membership.User.name), new RouteValueDictionary(new { controller = "blog", action = "index" }), "返回首页", MessageIcon.Message);
            }
        }

        [ActionName("logout")]
        public ActionResult Logout()
        {
            if (Fetch.IsGetFromAnotherDomain)
                return Message("提交数据非法", "请勿从非法站点提交数据.", MessageIcon.Error);
            if (Membership.User.id < 0)
                return Message("请先登陆系统", "您无权使用该功能,请先登陆系统.", new RouteValueDictionary(new { controller = "user", action = "login" }), "登陆系统", MessageIcon.Error);
            Membership.Logout();
            return Message("退出系统", "退出登录成功.", new RouteValueDictionary(new { controller = "blog", action = "index" }), "单击返回首页", MessageIcon.Message);
        }

        [ActionName("edit")]
        public ActionResult Edit()
        {
            if (Membership.User.id < 0)
                return Message("用户未登陆", "对不起,您无法进行该操作,请登陆后再进行.", MessageIcon.Error);
            Membership.LoadFull();
            ViewData.Model = Membership.User;
            title = string.Format("修改用户{0}的资料 - {0}", Membership.User.name, Config.Get(Provider).title);
            return View("edit");
        }

        public ActionResult EditPost()
        {
            if (Membership.User.id < 0)
                return Message("用户未登陆", "对不起,您无法进行该操作,请登陆后再进行.", MessageIcon.Error);
            Membership.LoadFull();
            string oldpassword = Request.Form["oldpassword"];
            string newpassword = Request.Form["password"];
            string newpassword2 = Request.Form["confirmpassword"];
            string nickname = Request.Form["nickname"];
            int sex = 0;
            int.TryParse(Request.Form["sex"], out sex);
            string mail = Request.Form["email"];
            string face = Request.Form["face"];
            string signature = Request.Form["signature"];
            if (Membership.User.password != oldpassword.ToMD5())
                return Message("您输入的密码有误.", "对不起,您输入的原密码有误.", MessageIcon.Error);
            if (newpassword != newpassword2)
                return Message("新密码输入错误", "对不起,您两次输入的新密码有误", MessageIcon.Error);
            if (!string.IsNullOrEmpty(newpassword))
                Membership.User.password = newpassword.ToMD5();
            Membership.User.userinfo.face = face.HtmlEncode();
            Membership.User.userinfo.mail = mail.HtmlEncode();
            Membership.User.userinfo.nickname = nickname.HtmlEncode();
            Membership.User.userinfo.sex = (short)sex;
            if ((Membership.Authority as Authority).PostHtml)
                Membership.User.userinfo.signature = signature;
            else
                Membership.User.userinfo.signature = signature.HtmlEncode();
            BlogUser.Update(Provider, Membership.User);
            Membership.Write();
            return Message("修改用户信息成功.", "恭喜,您修改用户信息成功", MessageIcon.Message);
        }

        [ActionName("view")]
        public ActionResult ViewUser(string name)
        {
            if (string.IsNullOrEmpty(name))
                return Message("空用户名", "请先指定查看的用户名", MessageIcon.Error);
            lb_user user = BlogUser.Get(Provider, name);
            if (user == null)
                return Message("不存在该用户", "对不起,不存在该用户或者该用户的数据已经被删除", MessageIcon.Error);
            ViewData.Model = user;
            title = string.Format("查看用户{0}的资料 - {1}", user.name, Config.Get(Provider).title);
            return View("view");
        }

        public ActionResult Reg(int? step)
        {
            if (!Config.Get(Provider).isreg)
                return Message("您无权进行该操作", "对不起,本站暂不提供用户注册.", MessageIcon.Error);
            step = step ?? 1;
            switch (step.Value)
            {
                case 1:
                default:
                    return View("reginfo");
                case 2:
                    return View("reg");
            }
        }

        public ActionResult RegPost()
        {
            if (!Config.Get(Provider).isreg)
                return Message("您无权进行该操作", "对不起,本站暂不提供用户注册.", MessageIcon.Error);
            string username = Request.Form["username"];
            string password = Request.Form["password"];
            string password2 = Request.Form["password2"];
            string code = Request.Form["code"];
            string mail = Request.Form["mail"];
            string nickname = Request.Form["nickname"];
            int sex = 0;
            int.TryParse(Request.QueryString["sex"], out sex);
            username = username == null ? string.Empty : username.Trim();
            password = password == null ? string.Empty : password.Trim();
            password2 = password2 == null ? string.Empty : password2.Trim();
            mail = mail == null ? string.Empty : mail.Trim();
            nickname = nickname == null ? string.Empty : nickname.Trim();
            if (username.Length < 2 || username.Length > 24)
                return Message("提交信息有误", "用户名由2到24个字符组成.", MessageIcon.Error);
            if (password != password2)
                return Message("提交信息有误", "两次提交的密码不相同.", MessageIcon.Error);
            if (password.Length < 6 | password.Length > 16)
                return Message("提交信息有误", "密码必须是6到16个字符，建议使用英文和符号混合.", MessageIcon.Error);
            if (string.IsNullOrEmpty(code))
                return Message("提交信息有误", "验证码不能为空", MessageIcon.Error);
            if (String.IsNullOrEmpty(mail) || !mail.IsMail()) {
                return Message("提交信息有误", "邮件格式错误", MessageIcon.Error);
            }
            HttpCookie codeCookie = Request.Cookies.Get(WebConfig.PrefixKey + "CheckCode");
            if (codeCookie == null)
            {
                return Message("验证码过期", "验证码过期,请返回重新输入.", MessageIcon.Error);
            }
            else
            {
                if (code.ToLower().ToMD5() != codeCookie.Value)
                    return Message("验证码错误", "验证码输入错误,请返回重新上输入.", MessageIcon.Error);
                else
                    Response.Cookies.Remove(WebConfig.PrefixKey + "CheckCode");
            }
            lb_user user = BlogUser.Get(Provider, username);
            if (user != null)
                return Message("该用户名不能注册", "对不起,该用户名已经被占用,请更换用户名后再次注册.", MessageIcon.Error);
            if (Config.Get(Provider).baduser.Split('|').Count(u => u.Trim() == username) > 0)
                return Message("该用户名不能注册", "对不起,该用户名不允许注册.", MessageIcon.Error);
            user = new lb_user();
            user.name = username.HtmlEncode();
            user.password = password.ToMD5();
            user.postnum = 0;
            user.typeid = 2; //默认注册用户
            user.userinfo = new lb_userinfo();
            user.userinfo.mail = mail;
            user.userinfo.nickname = nickname;
            user.userinfo.regip = Fetch.UserIp;
            user.userinfo.regtime = DateTime.Now;
            user.userinfo.sex = (short)sex;
            BlogUser.Insert(Provider, user);
            Membership.Login(user.name, password);
            return Message("用户注册成功", string.Format("恭喜{0},您已经注册成功并登陆,请返回首页查看.", username.HtmlEncode()), new { controller = "blog", action = "index" }, "返回首页", MessageIcon.Error);
        }
    }
}
